from fastapi import APIRouter, Depends, Form, Request
from pydantic_validation_decorator import ValidateFields
from sqlalchemy.ext.asyncio import AsyncSession
from config.enums import BusinessType
from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_admin.service.key_service import KeyService
from module_admin.entity.vo.key_vo import DeleteKeyModel, KeyModel, KeyPageQueryModel
from utils.common_util import bytes2file_response
from utils.log_util import logger
from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil
import uuid


keyController = APIRouter(
    prefix="/system/key", dependencies=[Depends(LoginService.get_current_user)]
)


@keyController.get("/my-list", response_model=PageResponseModel)
async def get_system_key_list(
    request: Request,
    key_page_query: KeyPageQueryModel = Depends(KeyPageQueryModel.as_query),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
    query_db: AsyncSession = Depends(get_db),
):
    # 获取分页数据
    key_page_query.user_id = current_user.user.user_id
    key_page_query_result = await KeyService.get_key_list_services(
        query_db, key_page_query, is_page=True
    )

    return ResponseUtil.success(model_content=key_page_query_result)


@keyController.get(
    "/list",
    response_model=PageResponseModel,
    dependencies=[Depends(CheckUserInterfaceAuth("system:key:list"))],
)
async def get_system_key_list(
    request: Request,
    key_page_query: KeyPageQueryModel = Depends(KeyPageQueryModel.as_query),
    query_db: AsyncSession = Depends(get_db),
):
    # 获取分页数据
    key_page_query_result = await KeyService.get_key_list_services(
        query_db, key_page_query, is_page=True
    )
    logger.info("获取成功")

    return ResponseUtil.success(model_content=key_page_query_result)


@keyController.post("")
@Log(title="API-KEY", business_type=BusinessType.INSERT)
async def add_system_key(
    request: Request,
    query_db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    userId = current_user.user.user_id
    key_page_query_result = await KeyService.get_key_list_services(
        query_db, KeyPageQueryModel(userId=userId), is_page=True
    )
    if key_page_query_result.total >= 3:
        return ResponseUtil.failure(msg="您最多只能有3个API Key")

    apiKey = "sk-" + str(uuid.uuid4()).replace("-", "")
    add_key = KeyModel(userId=current_user.user.user_id, apiKey=apiKey)
    add_key_result = await KeyService.add_key_services(
        request.app.state.redis, query_db, add_key
    )
    return ResponseUtil.success(msg=add_key_result.message)


@keyController.put(
    "", dependencies=[Depends(CheckUserInterfaceAuth("system:key:edit"))]
)
@ValidateFields(validate_model="edit_key")
@Log(title="API-KEY", business_type=BusinessType.UPDATE)
async def edit_system_key(
    request: Request,
    edit_key: KeyModel,
    query_db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    edit_key_result = await KeyService.edit_key_services(query_db, edit_key)
    logger.info(edit_key_result.message)

    return ResponseUtil.success(msg=edit_key_result.message)


@keyController.delete(
    "/{ids}", dependencies=[Depends(CheckUserInterfaceAuth("system:key:remove"))]
)
@Log(title="API-KEY", business_type=BusinessType.DELETE)
async def delete_system_key(
    request: Request, ids: str, query_db: AsyncSession = Depends(get_db)
):
    delete_key = DeleteKeyModel(ids=ids)
    delete_key_result = await KeyService.delete_key_services(
        request.app.state.redis, query_db, delete_key
    )
    logger.info(delete_key_result.message)

    return ResponseUtil.success(msg=delete_key_result.message)


@keyController.get(
    "/{id}",
    response_model=KeyModel,
    dependencies=[Depends(CheckUserInterfaceAuth("system:key:query"))],
)
async def query_detail_system_key(
    request: Request, id: int, query_db: AsyncSession = Depends(get_db)
):
    key_detail_result = await KeyService.key_detail_services(query_db, id)
    logger.info(f"获取id为{id}的信息成功")

    return ResponseUtil.success(data=key_detail_result)


@keyController.post(
    "/export", dependencies=[Depends(CheckUserInterfaceAuth("system:key:export"))]
)
@Log(title="API-KEY", business_type=BusinessType.EXPORT)
async def export_system_key_list(
    request: Request,
    key_page_query: KeyPageQueryModel = Form(),
    query_db: AsyncSession = Depends(get_db),
):
    # 获取全量数据
    key_query_result = await KeyService.get_key_list_services(
        query_db, key_page_query, is_page=False
    )
    key_export_result = await KeyService.export_key_list_services(key_query_result)
    logger.info("导出成功")

    return ResponseUtil.streaming(data=bytes2file_response(key_export_result))
